package com.open.demo.协程

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 * 协程(IO线程)，带返回值
 * 涉及知识点：泛型，扩展函数，高阶函数/lambda，单表达式函数，协程，LifecycleOwner
 */
fun <T> GlobalScope.ioAsync(lifecycleOwner: LifecycleOwner?=null,
                            start: CoroutineStart = CoroutineStart.DEFAULT,
                            block: suspend CoroutineScope.() -> T): Deferred<T> {
    // 协程
    val deferred = async(Dispatchers.IO, start) {
        block()
    }
    // 设置协程生命周期监听
    lifecycleOwner?.lifecycle?.addObserver(CoroutinesLifecycleObserver(deferred))
    return deferred
}

/**
 * 协程(UI线程)
 * infix 支持点的方式
 */
infix fun <T> Deferred<T>.then(block: (T) -> Unit) = GlobalScope.launch(Dispatchers.Main) {
    block(this@then.await())
}

/**
 * 协程生命周期监听
 */
open class CoroutinesLifecycleObserver(private val job: Job) : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun destroy() {
        if (!job.isCancelled) {
            job.cancel()
        }
    }
}

fun main() {
    GlobalScope.ioAsync {
        // 耗时操作
    } then {
        // UI刷新
    }
}